package com.tst.ums_pay

import android.content.Context
import android.os.Build
import com.chinaums.pppay.unify.UnifyPayPlugin
import com.chinaums.pppay.unify.UnifyPayRequest
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler

/** UmsPayPlugin  */
class UmsPayPlugin : FlutterPlugin, MethodCallHandler {
    private var channel: MethodChannel? = null
    private var context: Context? = null
    override fun onAttachedToEngine(flutterPluginBinding: FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ums_pay")
        channel!!.setMethodCallHandler(this)
        context = flutterPluginBinding.applicationContext
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "getPlatformVersion" -> {
                result.success("Android " + Build.VERSION.RELEASE)
            }

            "pay" -> {
                context?.let {
                    val channel = call.argument<String>("channel")
                    val data = call.argument<String>("data")
                    val msg = UnifyPayRequest()
                    msg.payChannel = UnifyPayRequest.CHANNEL_WEIXIN
                    msg.payData = data
                    UnifyPayPlugin.getInstance(it).sendPayRequest(msg)
                    val map: MutableMap<String, Any?> = HashMap()
                    map["code"] = "1000"
                    map["msg"] = channel
                    map["data"] = data
                    result.success(map)
                }

            }

            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
        channel!!.setMethodCallHandler(null)
    }
}
